package org.nf.web.view;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import org.nf.web.servlet.ServletApi;
import org.nf.web.servlet.View;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author zhu
 * @date 2024-05-20
 */
public class JsonView implements View {

    private final Object data;

    private final GsonBuilder gsonBuilder;

    public JsonView(Object data) {
        this.data = data;
        gsonBuilder = new GsonBuilder();
    }

    @Override
    public void render(ServletApi servletApi) throws ServletException, IOException {
        HttpServletResponse response = servletApi.resp();
        response.setContentType("application/json; charset=utf-8");
        String json = gsonBuilder.create().toJson(data);
        response.getWriter().write(json);
    }

    /**
     * 格式化日期
     *
     * @param pattern 日期格式
     */
    public void format(String pattern){
        gsonBuilder.setDateFormat(pattern);
        //构建LocalDateTime的json序列化器
        JsonSerializer<LocalDateTime> localDateTimeJsonSerializer = (localDateTime, type, jsonSerializationContext) ->
                new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern(pattern)));
        gsonBuilder.registerTypeAdapter(LocalDateTime.class, localDateTimeJsonSerializer);
        //构建LocalDate的json序列化器
        JsonSerializer<LocalDate> localDateJsonSerializer = (localDate, type, jsonSerializationContext) ->
                new JsonPrimitive(localDate.format(DateTimeFormatter.ofPattern(pattern)));
        gsonBuilder.registerTypeAdapter(LocalDate.class, localDateJsonSerializer);
        //构建LocalTime的json序列化器
        JsonSerializer<LocalTime> localTimeJsonSerializer = (localTime, type, jsonSerializationContext) ->
                new JsonPrimitive(localTime.format(DateTimeFormatter.ofPattern(pattern)));
        gsonBuilder.registerTypeAdapter(LocalTime.class, localTimeJsonSerializer);
    }
}
